package com.aerotechnic.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.aerotechnic.entities.User;
import com.aerotechnic.service.interfaces.JobcardBoIn;
import com.aerotechnic.service.interfaces.UserBoIn;

import javax.servlet.http.HttpSession;

@Controller
@SessionAttributes("userSession")
public class AthenController {
	@Autowired
	UserBoIn userBo;

	@Autowired
	JobcardBoIn jobCardBo;

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String renderDefaultView(ModelMap model, HttpSession session) {
		if (session.getAttribute("userSession") != null) {

			return "homePage";
		} else {
			
//			User user2Save = new User();
//			user2Save.setLogin("respo");
//			user2Save.setProfile("responsable Planning");
//			user2Save.setNom("ghaffari");
//			user2Save.setPrenom("el mehdi");
//			user2Save.setPassword("respo");
			// let's save

//			userBo.save(user2Save);
			
			User user = new User();
			model.addAttribute("user", user);

			// sending the page name
			model.addAttribute("pageName", "authentification");
			return "authentification";
		}

	}

	@RequestMapping(value = "/", method = RequestMethod.POST)
	public String triggerAuthentification1(ModelMap model,
			@ModelAttribute("user") User user, HttpSession session) {
		User fetchedUser = userBo.authenticate(user.getLogin(),
				user.getPassword());
		if (fetchedUser != null) {
			// the sessionn should never ever expire
			session.setMaxInactiveInterval(-1);
			
			model.addAttribute("userSession", fetchedUser);
			// 1 stands for admin, 2 responsable planning, 3 agent palanning
			if(fetchedUser.getProfile().equals("1")){
				return "redirect:/manageAccounts";
			}else{    
				
				return "homePage";
			}
			
		} else {
			model.addAttribute("error", "login ou mot de passe incorrect");
			return "authentification";
		}

	}

}